package org.biodas.jdas.client;

import org.biodas.jdas.client.adapters.sequence.DasSequenceAdapter;
import org.biodas.jdas.exceptions.DASClientException;
import org.biodas.jdas.schema.sequence.DASSEQUENCE;

import javax.xml.bind.JAXBException;

import java.io.IOException;
import java.util.List;

public class SequenceClient implements SequenceClientInterface {

	   ConnectionPropertyProviderI connectionProps = null;
	 
	   public SequenceClient()
	   {
	   }
	 
	   public SequenceClient(ConnectionPropertyProviderI connProps) {
	     this.connectionProps = connProps;
	   }

	/**
	 * Retrieves a sequence response.
	 * @param serverURL
	 * @param arguments
	 */
	private DasSequenceAdapter fetchData(String serverURL, String arguments) throws DASClientException {
        try {
            if (!serverURL.endsWith("/")) {
                serverURL += "/";
            }
            String url = serverURL + "sequence" + arguments;
            NoDtdJaxbParser parser=new NoDtdJaxbParser();
            return new DasSequenceAdapter((DASSEQUENCE)parser.parseXmlUrl(url,"org.biodas.jdas.schema.sequence",connectionProps));
		
        } catch (IOException e) {
			// TODO Auto-generated catch block
			throw new DASClientException(e.getMessage(), e.getCause());
		} catch (JAXBException e) {
			throw new DASClientException(e.getMessage(), e.getCause());
		}
	}

	/* (non-Javadoc)
	 * @see org.biodas.jdas.client.SequenceClientInterface#fetchData(java.lang.String, java.util.List)
	 */
	@Override
	public DasSequenceAdapter fetchData(String serverURL, List<String> segments) throws DASClientException {
        String arguments = "";
        String segmentArguments = null;
        if ((segments != null) && (segments.size() != 0)) {
            segmentArguments= "";
            for (String segment: segments) {
                segmentArguments += ";segment=" + segment;
            }
            segmentArguments = segmentArguments.substring(1); //we need to remove the first ;
        }
        if (segmentArguments != null) {
            arguments = arguments + "?" + segmentArguments;
        } 
        return this.fetchData(serverURL, arguments);
	}
}
